<!-- views/ListView.vue -->
<template>
  <div class="main-container">
      <div v-if="isModalOpen" class="modal-overlay">
      <div class="modal" @click.stop>
        <div class="modal-header">
          <div class="modal-first">
            <button class="modal-button-close" @click="closeModal">❌</button>
          </div>
          <div class="modal-second">
            <button class="modal-button" @click="sendToAITranslate">AI翻译</button>
            <button class="modal-button" @click="sendToAISentence">Ai例句</button>
            <button class="modal-button" @click="sendToAIStory">AI故事</button>
          </div>
        </div>
        <div class="modal-body">
          <p>{{ aiResponse }}</p>
        </div>
      </div>
    </div>

    <div class="vocabulary-container" @mouseup="handleMouseUp">
      <div v-if="currentQuestion" class="question">
        <h2>{{ currentQuestion.Question }}</h2>
        <div class="options">
          <button
            v-for="(option, index) in options"
            :key="index"
            :class="{
              selected: option === userSelection && !showResult,
              correct: option === currentQuestion['Correct Answer'] && showResult,
              incorrect: option === userSelection && !isCorrect && showResult
            }"
            @click="selectOption(option)"
            :disabled="showResult"
          >
            {{ option }}
          </button>
        </div>
        <button
          class="confirm-button"
          @click="confirmSelection"
          :disabled="userSelection === null || showResult"
        >
          ✅确认
        </button>
        <button
          class="next-button"
          @click="nextQuestion"
          :disabled="!showResult"
        >
          ➡️下一题
        </button>
      </div>
      <div v-else>
        <p>No more questions available.</p>
      </div>
    </div>
  </div>
</template>

<script setup>
import axios from 'axios';
import { ref ,onMounted,computed} from 'vue';
import config from '@/config';



/* ############################## */
/* 单词表加载 */
/* ############################## */
const wordList = ref([]);
const currentQuestion = ref(null);
const userSelection = ref(null);
const showResult = ref(false);

onMounted(async () => {
  try {
    const response = await fetch('./考研.json');
    const data = await response.json();
    wordList.value = data;

    // 确保单词表加载完成后初始化第一题
    currentQuestion.value = getRandomQuestion();
  } catch (error) {
    console.error('Error loading word list:', error);
  }
});

/* ############################## */
/* 选项逻辑 */
/* ############################## */

// 随机选择一个单词
const getRandomQuestion = () => {
  if (wordList.value.length === 0) {
    return null; // 如果单词表为空，返回 null
  }
  const randomIndex = Math.floor(Math.random() * wordList.value.length);
  return wordList.value[randomIndex];
};

// 选项列表
const options = computed(() => {
  if (!currentQuestion.value) return [];
  return [
    currentQuestion.value['Option A'],
    currentQuestion.value['Option B'],
    currentQuestion.value['Option C'],
    currentQuestion.value['Option D']
  ];
});

// 用户选择选项
const selectOption = (option) => {
  userSelection.value = option;
};

// 确认选择
const confirmSelection = () => {
  showResult.value = true;
};

// 判断是否选对
const isCorrect = computed(() => {
  return userSelection.value === currentQuestion.value['Correct Answer'];
});

// 下一题
const nextQuestion = () => {
  userSelection.value = null;
  showResult.value = false;
  currentQuestion.value = getRandomQuestion();
};



/* ############################## */
/* ai交互类 */
/* ############################## */



//openai接口
// 发送请求到 OpenAI，并获取代码
const fetchOpenAILite = async (vocabulary,userOption) => {
  const systemMessage = { role: 'system', content: `你是一个英语对话助手，帮助，用户解释单词或句子，回复纯文本内容,简要回答，尽量不超过3句话` };
  const aimessage = [systemMessage];
  aimessage.push({
      role: 'user',
      content: userOption+vocabulary
    })
  try {
    const response = await axios.post(config.apiUrl + 'openai_proxy.php', {
      messages: aimessage // 发送聊天记录
    }, {
      headers: {
        'Content-Type': 'application/json'
      }
    });

    // 处理并返回 OpenAI 响应
    const { choices } = response.data;
    const code = choices && choices[0] ? choices[0].message.content : '';

    // 返回生成的代码和完整的 OpenAI 响应
    return {
      code, // 返回生成的代码
      rawResponse: response.data, // 返回完整的 OpenAI API 响应
    };

  } catch (error) {
    console.error('API调用失败:', error);
    throw new Error(`生成失败: ${error.message}`);
  }
};


const selectedText = ref('');
const aiResponse = ref('');
const isModalOpen = ref(false);
const isUsingAi = ref(false);
// 捕获用户选择的文本
const handleMouseUp = () => {
  const selection = window.getSelection().toString().trim();
  if (selection) {
    selectedText.value = selection;
    isModalOpen.value = true;
    aiResponse.value = selectedText.value;
  }
};

// 发送到 AI 并接收响应
const sendToAITranslate = async () => {
  isUsingAi.value=true;
  try {
    const response = await  fetchOpenAILite(selectedText.value,"给出以下英语句子或单词的翻译：");
    console.log(response)
    aiResponse.value = response.code
    isUsingAi.value=false;
  } catch (error) {
    console.log(error.message);
    isUsingAi.value=false;
  }
};
const sendToAISentence = async () => {
  isUsingAi.value=true;
  try {
    const response = await  fetchOpenAILite(selectedText.value,"给出以下英语句子或单词的例句，还包含中文翻译：");
    console.log(response)
    aiResponse.value = response.code
    isUsingAi.value=false;
  } catch (error) {
    console.log(error.message);
    isUsingAi.value=false;
  }
};
const sendToAIStory = async () => {
  isUsingAi.value=true;
  try {
    const response = await  fetchOpenAILite(selectedText.value,"根据以下英语句子或单词，写一段小故事，不超过50词：");
    console.log(response)
    aiResponse.value = response.code
    isUsingAi.value=false;
  } catch (error) {
    console.log(error.message);
    isUsingAi.value=false;
  }
};


const closeModal = () => {
  if(isUsingAi.value==false)
  {
    isModalOpen.value = false;
    aiResponse.value = '';
  }
};

</script>

<style scoped>
/* ############################## */
/* 主容器 */
/* ############################## */
.main-container{
  height:100vh;
  background: linear-gradient(
    135deg,
    #f5f7fa 0%,     /* 柔和的云朵白 */
    #e3e9ff 25%,    /* 浅薰衣草灰 */
    #d8e4ff 50%,    /* 极淡的婴儿蓝 */
    #eceffd 75%,    /* 细腻的月光银 */
    #f5f7fa 100%    /* 与起始颜色呼应形成无缝循环 */
  );
  background-size: 100% 100%; /* 更紧凑的背景尺寸提升细腻度 */
  animation: gradient 5s ease infinite; /* 更缓和的动画节奏 */
}
@keyframes gradient {
  0% {
    background-position: 0% 50%;
  }
  50% {
    background-position: 100% 50%;
  }
  100% {
    background-position: 0% 50%;
  }
}

/* 竖屏模式下主容器上移 5vw */
@media (max-width: 768px) and (orientation: portrait) {
  .main-container {
    margin-bottom: 5vw; /* 向上移动 5vw */
    margin-left: 0px;
  }
}

/* ############################## */
/* 单词框 */
/* ############################## */
.vocabulary-container {
  text-align: center;
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 30vw;
  height: 80vh;
  overflow-y: none;
  padding: 10px;
  background: rgba(245, 245, 245, 0.5); /* 半透明背景 */
  backdrop-filter: blur(10px); /* 毛玻璃效果 */
  border-radius: 16px; /* 圆角效果 */
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1); /* 阴影效果 */
  box-sizing: border-box;
  z-index: 1000;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
}


/* ############################## */
/* 选项 */
/* ############################## */
.question {
  margin-bottom: 20px;
}

.options button {
  margin: 5px 0;
  padding: 12px;
  width: 100%;
  border: 1px solid #e0e0e0; /* 轻微边框 */
  border-radius: 8px; /* 圆润的边角 */
  font-size: 16px;
  font-weight: 500;
  color: #333; /* 深灰色文字 */
  cursor: pointer;
  transition: all 0.3s ease; /* 平滑过渡 */
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05); /* 轻微阴影 */
}
.options button.selected {
  background-color: #e8f5e9; /* 淡绿色背景 */
  border-color: #90be90;
  color: #285943; /* 深绿色文字 */
  box-shadow: 0 2px 4px rgba(76, 175, 80, 0.1);
}
.options button:hover {
  transform: translateY(-1px); /* 悬停时轻微上升 */
}

.correct {
  background-color: #e6f4ea; /* 淡绿色 */
  border-color: #90be90;
  color: #285943; /* 深绿色文字 */
  box-shadow: 0 2px 4px rgba(76, 175, 80, 0.1);
}

.incorrect {
  background-color: #fce8e8; /* 淡红色 */
  border-color: #e67e7e;
  color: #a92b2b; /* 深红色文字 */
  box-shadow: 0 2px 4px rgba(244, 67, 54, 0.1);
}

.confirm-button,
.next-button {
  margin-top: 10px;
  padding: 12px;
  width: 60%;
  background-color: #007aff; /* iOS 主色调 */
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 500;
  color: white;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 2px 4px rgba(0, 122, 255, 0.3);
}

.confirm-button:hover,
.next-button:hover {
  background-color: #0062cc; /* 悬停时稍微变深 */
  transform: translateY(-1px);
}

.confirm-button:disabled,
.next-button:disabled {
  background-color: #cccccc; /* 灰色 */
  box-shadow: none;
  cursor: not-allowed;
}



/* ############################## */
/* ai模态窗 */
/* ############################## */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index:1001;
}

.modal {
  position: relative;
  background: rgba(255, 255, 255, 0.4);
  backdrop-filter: blur(10px);
  -webkit-backdrop-filter: blur(10px); /* Safari 兼容 */
  padding: 20px;
  border-radius: 16px;
  width: 20vw;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
  z-index: 1001;
}

.modal-header {
  display: block; /* 或者不使用 flex */
  margin-bottom: 40px;
  position: relative;
}

.modal-first {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 10px; /* 添加间距 */
  height:20px;
}

.modal-second {
  display: flex;
  gap: 10px;
}

.modal-button {
  padding: 10px 15px; /* 内边距 */
  border: none; /* 移除边框 */
  border-radius: 20px; /* 圆角 */
  background-color: #87CEEB; /* 淡雅的浅蓝色 */
  color: white; /* 文字颜色 */
  cursor: pointer; /* 鼠标指针样式 */
  font-size: 14px; /* 字体大小 */
  font-weight: 500; /* 字体粗细 */
  transition: all 0.3s ease; /* 平滑过渡效果 */
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); /* 阴影效果 */
  outline: none; /* 移除默认的焦点轮廓 */
}

/* 悬停效果 */
.modal-button:hover {
  background-color: #77B5E7; /* 悬停时更深的浅蓝色 */
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2); /* 增加阴影 */
  transform: translateY(-2px); /* 微微上移 */
}

/* 按下效果 */
.modal-button:active {
  background-color: #66A3D2; /* 按下时更深的浅蓝色 */
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); /* 减少阴影 */
  transform: translateY(0); /* 恢复位置 */
}

/* 焦点状态 */
.modal-button:focus {
  outline: 2px solid rgba(255, 255, 255, 0.5); /* 焦点时的轮廓 */
  outline-offset: 2px; /* 轮廓偏移 */
}

.modal-button:hover {
  background-color: #0062cc;
}

.modal-button-close {
  border: none; /* 移除边框 */
  font-size: 16px; /* 设置字体大小 */
  top: 0; /* 定位到顶部 */
  right: 0; /* 定位到右侧 */
  background: none; /* 移除背景 */
  cursor: pointer; /* 添加鼠标指针样式，表示可点击 */
  padding: 5px; /* 添加一些内边距，便于点击 */
}

.modal-body {
  font-size: 16px;
  color: #333;
  text-align: center;
}


/* ############################## */
/* 竖屏响应 */
/* ############################## */
@media (orientation: portrait) {
.vocabulary-container {
  text-align: center;
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 90vw;
  height: 80vh;
}
}
</style>